package com.pansoft.kline.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.activity.ShareToZoneActivity;
import com.efounder.chat.model.ShareContent;
import com.efounder.chat.utils.HandleShareIntentUtil;
import com.efounder.chat.utils.SystemShareHelper;
import com.efounder.utils.ResStringUtil;
import com.efounder.viewpagerindicator.CirclePageIndicator;
import com.pansoft.kline.adapter.GridViewPagerAdapter;
import com.pansoft.kline.adapter.ShareMenuGridViewAdapter;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.ShareMenuBean;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.utilcode.util.FileUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author will
 * 分享行情界面
 */
public class ShareKLineActivity extends BaseActivity implements View.OnClickListener {

    public static int item_grid_num = 8;//每一页中GridView中item的数量
    public static int number_columns = 4;//gridview一行展示的数目

    private ReflectUtils reflectUtils;
    private String filePath, fileNoBarcodePath;
    private UMImage web;
    private String currentTime;

    private ImageView imageView;
    private ViewPager viewPager;
    private GridViewPagerAdapter mAdapter;
    private ShareMenuGridViewAdapter gridAdapter;
    private CirclePageIndicator indicator;

    private List<ShareMenuBean> shareMenuBeans = new ArrayList<>();
    private List<GridView> gridList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_share_k_line);
        currentTime = TimeUtils.getNowString();
        try {
            reflectUtils = ReflectUtils.reflect(ResStringUtil.getString(com.efounder.mobilemanager.R.string.manager_share_screen_shot_class));
            reflectUtils = reflectUtils.newInstance();
        } catch (Exception e) {
            LogUtils.e("com.efounder.UShareScreenShotHelper未找到,不初始化截图功能");
        }
        initView();
        initData();
    }

    public static void start(Context context, String filePath, String fileNoBarcodePath) {
        Intent starter = new Intent(context, ShareKLineActivity.class);
        starter.putExtra("filePath", filePath);
        starter.putExtra("fileNoBarcodePath", fileNoBarcodePath);
        context.startActivity(starter);
    }

    private void initView() {

        imageView = (ImageView) findViewById(R.id.iv_share_image);

        findViewById(R.id.tv_left_close).setVisibility(View.VISIBLE);
        findViewById(R.id.tv_left_close).setOnClickListener(this);
        findViewById(R.id.iv_back).setVisibility(View.GONE);
        ((TextView) findViewById(R.id.tv_title)).setText(R.string.open_planet_share_image);
        findViewById(R.id.tv_save).setVisibility(View.VISIBLE);
        findViewById(R.id.tv_save).setOnClickListener(this);

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        indicator = (CirclePageIndicator) findViewById(R.id.indicator);

        mAdapter = new GridViewPagerAdapter();
        viewPager.setAdapter(mAdapter);
        indicator.setVisibility(View.VISIBLE);
        indicator.setViewPager(viewPager);
    }

    private void initData() {
        filePath = getIntent().getStringExtra("filePath");
        fileNoBarcodePath = getIntent().getStringExtra("fileNoBarcodePath");
        Bitmap bitmap = getLoacalBitmap(filePath);
        imageView.setImageBitmap(bitmap);
  //      LXGlideImageLoader.getInstance().displayImage(this, imageView, filePath);
        web = new UMImage(this, new File(filePath));
        generateMenuItems();
        initViewPager();
    }
    /**
     * 加载本地图片
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    private void initViewPager() {
        //计算viewpager一共显示几页
        int pageSize = shareMenuBeans.size() % item_grid_num == 0
                ? shareMenuBeans.size() / item_grid_num
                : shareMenuBeans.size() / item_grid_num + 1;
        for (int i = 0; i < pageSize; i++) {
            GridView gridView = new GridView(this);
            gridAdapter = new ShareMenuGridViewAdapter(shareMenuBeans, i);
            gridAdapter.setOnItemSelectedListener(new ShareMenuGridViewAdapter.OnItemSelectedListener() {
                @Override
                public void onItemSelected(String name) {
                    dealWithMenuClicked(name);
                }
            });
            gridView.setNumColumns(number_columns);
            gridView.setAdapter(gridAdapter);
            gridList.add(gridView);
        }
        mAdapter.add(gridList);
    }

    private void generateMenuItems() {
        ShareMenuBean shareMenuBean1 = new ShareMenuBean(R.drawable.wechat_share_friend,
                ResStringUtil.getString(R.string.openplanet_share_helper_contacts));
        shareMenuBeans.add(shareMenuBean1);
        ShareMenuBean shareMenuBean2 = new ShareMenuBean(R.drawable.wechat_share_zone,
                ResStringUtil.getString(R.string.zone_gravity_field));
        shareMenuBeans.add(shareMenuBean2);
        ShareMenuBean shareMenuBean3 = new ShareMenuBean(R.drawable.umeng_socialize_sina,
                ResStringUtil.getString(R.string.openplanet_share_helper_sina));
        shareMenuBeans.add(shareMenuBean3);
        ShareMenuBean shareMenuBean4 = new ShareMenuBean(R.drawable.umeng_socialize_wechat,
                ResStringUtil.getString(R.string.openplanet_share_helper_wechat));
        shareMenuBeans.add(shareMenuBean4);
        ShareMenuBean shareMenuBean5 = new ShareMenuBean(R.drawable.umeng_socialize_wxcircle,
                ResStringUtil.getString(R.string.openplanet_share_helper_wxcircle));
        shareMenuBeans.add(shareMenuBean5);
        ShareMenuBean shareMenuBean8 = new ShareMenuBean(R.drawable.umeng_socialize_fav,
                ResStringUtil.getString(R.string.openplanet_share_helper_wechatfavorite));
        shareMenuBeans.add(shareMenuBean8);
        ShareMenuBean shareMenuBean6 = new ShareMenuBean(R.drawable.umeng_socialize_qq,
                ResStringUtil.getString(R.string.openplanet_share_helper_qq));
        shareMenuBeans.add(shareMenuBean6);
        ShareMenuBean shareMenuBean7 = new ShareMenuBean(R.drawable.umeng_socialize_qzone,
                ResStringUtil.getString(R.string.openplanet_share_helper_qzone));
        shareMenuBeans.add(shareMenuBean7);
        ShareMenuBean shareMenuBean9 = new ShareMenuBean(R.drawable.wechatview_share_system,
                ResStringUtil.getString(R.string.openplanet_share_helper_share_system));
        shareMenuBeans.add(shareMenuBean9);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_save) {
            //文件保存路径
            final String newFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator
                    + ResStringUtil.getString(R.string.chart_trend) + currentTime + ".png";
            FileUtils.copyFile(filePath, newFilePath, new FileUtils.OnReplaceListener() {
                @Override
                public boolean onReplace() {
                    return true;
                }
            });
            ToastUtils.showShort(ResStringUtil.getString(R.string.chat_photo_save_to) + newFilePath);
        } else if (id == R.id.tv_left_close) {
            finish();
        }
    }

    private void dealWithMenuClicked(String name) {
        //分享给联系人
        if (ResStringUtil.getString(R.string.openplanet_share_helper_contacts).equals(name)) {
            sendToFriend(ShareKLineActivity.this, fileNoBarcodePath, fileNoBarcodePath, "", null);
            //新浪
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_sina).equals(name)) {
            sharePlatform(ShareKLineActivity.this, SHARE_MEDIA.SINA, web);
            //微信
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_wechat).equals(name)) {
            sharePlatform(ShareKLineActivity.this, SHARE_MEDIA.WEIXIN, web);
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_wxcircle).equals(name)) {
            //朋友圈
            sharePlatform(ShareKLineActivity.this, SHARE_MEDIA.WEIXIN_CIRCLE, web);
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_wechatfavorite).equals(name)) {
            //收藏
            sharePlatform(ShareKLineActivity.this, SHARE_MEDIA.WEIXIN_FAVORITE, web);
            //qq
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_qq).equals(name)) {
            sharePlatform(ShareKLineActivity.this, SHARE_MEDIA.QQ, web);
            //qq空间
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_qzone).equals(name)) {
            sharePlatform(ShareKLineActivity.this, SHARE_MEDIA.QZONE, web);
            //系统
        } else if (ResStringUtil.getString(R.string.openplanet_share_helper_share_system).equals(name)) {
            SystemShareHelper.shareOneImage(this, filePath);
            //引力场
        } else if (ResStringUtil.getString(R.string.zone_gravity_field).equals(name)) {
            ShareContent shareContent = new ShareContent();
            shareContent.setType(HandleShareIntentUtil.SHARE_TYPE_IMAGE);
            ArrayList<String> pictureList = new ArrayList<>();
            pictureList.add(fileNoBarcodePath);
            shareContent.setPictureList(pictureList);
            Intent intent = new Intent(this, ShareToZoneActivity.class);
            intent.putExtra("imageMinorCompress", true);
            intent.putExtra("isLocalShare", true);
            intent.putExtra("shareContent", shareContent);
            startActivity(intent);
        }
    }

    /**
     * 发送给联系人（发送原始图片文件）
     *
     * @param context
     * @param filePath
     * @param title       原始截图文件
     * @param description
     * @param groupId
     */
    private void sendToFriend(final Context context, final String filePath, final String title
            , final String description, Object groupId) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(title)));

            //通过主工程配置 可以获取到要跳转的界面
            String className = "com.efounder.chat.activity.MobileShareActivity";
            Class clazz = Class.forName(className);
            intent.setClass(context, clazz);
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 分享自带的平台方法
     *
     * @param context
     * @param share_media
     * @param umImage
     */
    private void sharePlatform(final Context context, SHARE_MEDIA share_media, UMImage umImage) {
        new ShareAction((Activity) context).setPlatform(share_media).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
//                Toast.makeText(context, "分享成功!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
//                Toast.makeText(context, "分享失败!" + throwable.getMessage(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
//                Toast.makeText(context, "取消分享!", Toast.LENGTH_SHORT).show();

            }
        })
                //.withText("分享")
                .withMedia(umImage)
                .share();
    }
}
